<?php

namespace app\model;

use support\Model;

class UserModel extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'user';

    /**
     * The primary key associated with the table.
     *
     * @var string
     */
    protected $primaryKey = 'id';

    /**
     * Indicates if the model should be timestamped.
     *
     * @var bool
     */
    public $timestamps = false;

    /**
     * 可批量赋值字段
     * @var array
     */
    protected $fillable = [
        'open_id',
        'phone',
        'nickname',
        'headimg',
        'access_token',
        'vip_at',
        'score',
        'in_black',
        'sex',
        'birthday',
        'created_at',
        'updated_at'
    ];

    public static function userCache($id){
        $data = UserModel::find($id);
        $data['avatar'] = Util::pathToUrl($data->headimg);
        $data['safe_phone'] = substr_replace($data->phone, '****', 3, 4);
        return $data;
    }

    public function isVip(){
        return $this->vip_at > 0 && $this->vip_at > time();
    }

    public function safePhone(){
        return substr_replace($this->phone, '****', 3, 4);
    }

    public function headimgToUrl(){
        return empty($this->headimg) ? null : Util::pathToUrl($this->headimg);
    }

}